package com.ruoyi.system;


import org.springframework.stereotype.Service;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
/**
 * WebSocket
 */
@Service
//@ServerEndpoint("/websocket/data/{sid}")
public class WebStocketService extends TextWebSocketHandler {


    private Session session;

    private String sid ="";


 private   static CopyOnWriteArraySet<WebStocketService> webStocket  =   new CopyOnWriteArraySet<>();


  @OnOpen
  public  void  onOpen(Session session, @PathParam("sid") String sid){
      this.session =session;
      this.sid = sid;
      webStocket.add(this);

      System.out.println("sid:"+sid);
      try {
           sendMessage("链接成功");
      }catch (IOException e){

      }
  }


  @OnClose
  public  void  onClose(){
            webStocket.remove(this);
  }


  @OnMessage
  public void onMessage(String message, Session session){

  }

  @OnError
  public void onError(Session session, Throwable error){
      error.printStackTrace();
  }


  //指定人发消息
    public static void sendMessage(String message , String sid) throws IOException {
      for (WebStocketService item : webStocket){
          if (sid.equals(item.sid)){
              item.sendMessage(message);
          }
      }
    }



    private void sendMessage(String message) throws IOException {
            this.session.getBasicRemote().sendText(message);
    }

}
